package curator.count;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.atomic.DistributedAtomicInteger;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by zhang on 2017/3/15.
 *
 * 分布式锁
 *
 */
public class ZkAtomicCount {

    private static final String ZK_ADDR = "127.0.0.1:2181" ;
    private static final String COUNT_PATH = "/count" ;

    public static void main(String[] args)throws Exception{
        RetryPolicy policy = new ExponentialBackoffRetry( 1000 ,3);
        CuratorFramework client = CuratorFrameworkFactory.newClient(ZK_ADDR,policy);
        client.start();


        DistributedAtomicInteger count = new DistributedAtomicInteger(client,COUNT_PATH,policy);


        ExecutorService service = Executors.newFixedThreadPool(4);

        service.execute(()->{
            try {
                Thread.sleep(3000);
                System.out.println(count.increment().postValue());
            }catch (Exception e){
                e.printStackTrace();
            }
        });
        service.execute(()->{
            try {
                Thread.sleep(3000);
                System.out.println(count.increment().postValue());
            }catch (Exception e){
                e.printStackTrace();
            }
        });

        service.execute(()->{
            try {
                Thread.sleep(3000);
                System.out.println(count.increment().postValue());
            }catch (Exception e){
                e.printStackTrace();
            }
        });





        Thread.sleep(5000);

        service.shutdown();
    }




}
